<template>
  <el-dialog v-model="visible" title="新增下一级设备" width="95%" top="5vh">
    <!-- 可滚动区域 -->
    <div class="table-wrapper" ref="tableWrapper">
      <el-table
        :data="rows"
        border
        style="width: 100%"
        :header-cell-style="{ background: '#f9fafb', fontWeight: 600 }"
        :row-style="getRowStyle"
      >
        <el-table-column prop="parentName" label="类型" min-width="160">
          <template #default="{ row, $index }">
            <div :style="{ paddingLeft: `${row.indentLevel * 20}px` }">
              <el-select v-model="row.nodeType" @change="onTypeChange($index)">
                <el-option
                  v-for="opt in getTypeOptions()"
                  :key="opt.value"
                  :label="opt.label"
                  :value="opt.value"
                />
              </el-select>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="nodeType" label="上一级名称" min-width="120">
          <template #default="{ row, $index }">
            <el-select
              v-model="row.parentName"
              placeholder="请选择上一级名称"
              @change="onParentNameChange"
            >
              <el-option
                v-for="opt in getParentNameOptions(row.nodeType, $index)"
                :key="opt.value"
                :label="opt.label"
                :value="opt.value"
              />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column prop="name" label="名称" min-width="150">
          <template #default="{ row }">
            <el-input v-model="row.name" @input="onNameChange" />
          </template>
        </el-table-column>

        <el-table-column prop="beType" label="类别" min-width="120">
          <template #default="{ row }">
            <el-input v-model="row.beType" />
          </template>
        </el-table-column>

        <el-table-column prop="mokuai" label="模块" min-width="120">
          <template #default="{ row }">
            <el-input v-model="row.mokuai" />
          </template>
        </el-table-column>

        <el-table-column prop="area" label="区域" min-width="120">
          <template #default="{ row }">
            <el-input v-model="row.area" />
          </template>
        </el-table-column>

        <el-table-column prop="specification" label="规格" min-width="150">
          <template #default="{ row }">
            <el-input v-model="row.specification" />
          </template>
        </el-table-column>

        <el-table-column prop="material" label="材质" min-width="120">
          <template #default="{ row }">
            <el-input v-model="row.material" />
          </template>
        </el-table-column>

        <el-table-column prop="unit" label="单位" min-width="100">
          <template #default="{ row }">
            <el-input v-model="row.unit" />
          </template>
        </el-table-column>

        <el-table-column prop="quantity" label="数量" min-width="120">
          <template #default="{ row }">
            <el-input-number v-model="row.quantity" :min="0" />
          </template>
        </el-table-column>

        <el-table-column prop="amount" label="金额(万)" min-width="120">
          <template #default="{ row }">
            <el-input-number v-model="row.amount" :min="0" />
          </template>
        </el-table-column>

        <el-table-column prop="designTemp" label="设计温度(℃)" min-width="130">
          <template #default="{ row }">
            <el-input-number v-model="row.designTemp" />
          </template>
        </el-table-column>

        <el-table-column
          prop="designPress"
          label="设计压力(MPa)"
          min-width="130"
        >
          <template #default="{ row }">
            <el-input-number v-model="row.designPress" />
          </template>
        </el-table-column>

        <el-table-column prop="motorPower" label="电机功率(KW)" min-width="130">
          <template #default="{ row }">
            <el-input-number v-model="row.motorPower" />
          </template>
        </el-table-column>

        <el-table-column prop="mixingType" label="搅拌形式" min-width="120">
          <template #default="{ row }">
            <el-input v-model="row.mixingType" />
          </template>
        </el-table-column>

        <el-table-column prop="brand" label="品牌" min-width="120">
          <template #default="{ row }">
            <el-input v-model="row.brand" />
          </template>
        </el-table-column>

        <el-table-column prop="manufacturer" label="厂家" min-width="120">
          <template #default="{ row }">
            <el-input v-model="row.manufacturer" />
          </template>
        </el-table-column>

        <el-table-column prop="remark" label="备注" min-width="180">
          <template #default="{ row }">
            <el-input v-model="row.remark" />
          </template>
        </el-table-column>

        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ $index }">
            <el-button link type="primary" @click="copyRow($index)"
              >复制</el-button
            >
            <el-button link type="warning" @click="clearRow($index)"
              >清空</el-button
            >
            <el-button link type="danger" @click="removeRow($index)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 底部按钮 -->
    <div class="add-btn">
      <el-button type="success" plain size="small" @click="addRow"
        >＋ 新增一行</el-button
      >
      <el-button type="info" plain size="small" @click="scrollToLeft"
        >⬅ 回到最左边</el-button
      >
    </div>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="confirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { reactive, ref, watch, nextTick } from "vue";
import { ElMessage } from "element-plus";

const emit = defineEmits(["confirm"]);

const visible = ref(false);
const rows = reactive([]);
const parentItem = ref(null);
const tableWrapper = ref(null);

const ORDER = ["SYSTEM", "MACHINE", "MODULE", "COMPONENT", "PART"];

// ✅ 缓存
const lastCache = reactive({});
const cacheKey = ref("");

// ✅ 计算每行缩进级别
function getRowStyle({ row, rowIndex }) {
  let indentLevel = 0;
  if (rowIndex > 0) {
    const prevRow = rows[rowIndex - 1];
    if (row.parentName === prevRow.name && row.parentName && prevRow.name) {
      indentLevel = (prevRow.indentLevel || 0) + 1;
    }
  }
  row.indentLevel = indentLevel; // 存储缩进级别
  console.log(
    `Row ${rowIndex + 1}: parentName=${row.parentName}, name=${
      row.name
    }, indentLevel=${indentLevel}`
  ); // 调试日志
  // return {
  //   paddingLeft: `${indentLevel * 20}px !important`,
  // };
}

// ✅ 打开弹窗
function open(item) {
  visible.value = true;
  parentItem.value = item || {};

  const key = `${item.nodeType}_${item.uid || item.id || Date.now()}`;
  cacheKey.value = key;

  if (lastCache[key] && Array.isArray(lastCache[key])) {
    const cachedRows = JSON.parse(JSON.stringify(lastCache[key]));
    rows.splice(0, rows.length, ...cachedRows);
  } else {
    rows.splice(0, rows.length);
    rows.push(makeEmptyRow(item.name, nextType(item.nodeType)));
  }

  // 同步缓存父级名称
  if (cacheKey.value && lastCache[cacheKey.value]) {
    lastCache[cacheKey.value].forEach((r) => {
      if (r.nodeType === "MODULE") {
        r.parentName = item.name || "";
      }
    });
  }

  nextTick(() => {
    rows.forEach((r, index) => {
      if (!getTypeOptions().some((opt) => opt.value === r.nodeType)) {
        r.nodeType = getTypeOptions()[0]?.value || "";
      }
      if (
        !getParentNameOptions(r.nodeType, index).some(
          (opt) => opt.value === r.parentName
        )
      ) {
        r.parentName = getParentNameOptions(r.nodeType, index)[0]?.value || "";
      }
    });
  });
}

// 获取父级名称选项
function getParentNameOptions(nodeType, index) {
  const options = [];
  const parentName = parentItem.value?.name?.trim();

  if (parentName) {
    options.push({ label: parentName, value: parentName });
  }

  if (nodeType === "MODULE") {
    // MODULE 的父级只能是父节点（parentItem）
  } else if (nodeType === "COMPONENT") {
    rows.forEach((row, i) => {
      if (i < index && row.nodeType === "MODULE" && row.name?.trim()) {
        options.push({ label: row.name, value: row.name });
      }
    });
  } else if (nodeType === "PART") {
    rows.forEach((row, i) => {
      if (
        i < index &&
        (row.nodeType === "COMPONENT" || row.nodeType === "MODULE") &&
        row.name?.trim()
      ) {
        options.push({ label: row.name, value: row.name });
      }
    });
  }

  if (!options.length) {
    options.push({ label: parentName || "无", value: parentName || "" });
  }

  return options;
}

function getTypeOptions() {
  const pType = parentItem.value?.nodeType || "";
  switch (pType) {
    case "MACHINE":
      return [
        { label: "子设备", value: "MODULE" },
        { label: "部件", value: "COMPONENT" },
        { label: "零件", value: "PART" },
      ];
    case "MODULE":
      return [
        { label: "部件", value: "COMPONENT" },
        { label: "零件", value: "PART" },
      ];
    case "COMPONENT":
      return [{ label: "零件", value: "PART" }];
    default:
      return [
        { label: "子设备", value: "MODULE" },
        { label: "部件", value: "COMPONENT" },
        { label: "零件", value: "PART" },
      ];
  }
}

// 自动推导下一级类型
function nextType(type) {
  const idx = ORDER.indexOf(type);
  return ORDER[idx + 1] || "PART";
}

// 构造新行
function makeEmptyRow(customParentName, forcedType) {
  const p = parentItem.value || {};
  const defaultType = forcedType || nextType(p.nodeType);
  const parentName = customParentName || p.name || "";

  const base = {
    uid: Math.random().toString(36).slice(2),
    parentName,
    nodeType: defaultType,
    code: "",
    name: "",
    beType: "",
    mokuai: "",
    area: "",
    specification: "",
    material: "",
    unit: "台",
    quantity: 0,
    amount: 0,
    designTemp: 0,
    designPress: 0,
    motorPower: 0,
    mixingType: "",
    brand: "",
    manufacturer: "",
    remark: "",
    indentLevel: 0,
  };

  if (p.nodeType === "MACHINE") {
    base.mokuai = p.mokuai || "";
    base.area = p.area || "";
    base.specification = p.specification || "";
    base.material = p.material || "";
    base.unit = p.unit || "";
  }

  return base;
}

// 操作函数
function findNearest(type) {
  for (let i = rows.length - 1; i >= 0; i--) {
    const r = rows[i];
    if (r.nodeType === type && r.name && r.name.trim()) return r;
  }
  return null;
}

function addRow() {
  const last = rows[rows.length - 1];
  let next;
  let parentName = parentItem.value?.name || "";

  // 当最后一行是 PART 时，强制新行类型为 MODULE，并设置 parentName 为 parentItem 的名称
  if (last.nodeType === "PART") {
    next = "MODULE";
    parentName = parentItem.value?.name || "";
  } else {
    next = last.nodeType === "PART" ? "PART" : nextType(last.nodeType);
    if (next === "MODULE") {
      parentName = last.name?.trim() || parentItem.value?.name || "";
    } else if (next === "COMPONENT") {
      const mod = findNearest("MODULE");
      parentName = mod ? mod.name : parentItem.value?.name || "";
    } else if (next === "PART") {
      const comp = findNearest("COMPONENT");
      if (comp) {
        parentName = comp.name;
      } else {
        const mod = findNearest("MODULE");
        parentName = mod ? mod.name : parentItem.value?.name || "";
      }
    }
  }

  rows.push(makeEmptyRow(parentName, next));
}

function onTypeChange(index) {
  const r = rows[index];
  if (!r) return;

  let parentName = parentItem.value?.name || "";
  const findNearest = (type) => {
    for (let i = index - 1; i >= 0; i--) {
      const x = rows[i];
      if (x.nodeType === type && x.name && x.name.trim()) return x;
    }
    return null;
  };

  switch (r.nodeType) {
    case "MODULE":
      parentName = parentItem.value?.name || "";
      break;
    case "COMPONENT":
      const mod = findNearest("MODULE");
      parentName = mod ? mod.name : parentItem.value?.name || "";
      break;
    case "PART":
      const comp = findNearest("COMPONENT");
      if (comp) {
        parentName = comp.name;
      } else {
        const mod = findNearest("MODULE");
        parentName = mod ? mod.name : parentItem.value?.name || "";
      }
      break;
  }

  r.parentName = parentName;
}

function onParentNameChange() {
  // 强制触发重新计算缩进
  rows.forEach((row, index) => {
    row.indentLevel = 0; // 重置以重新计算
    if (index > 0) {
      const prevRow = rows[index - 1];
      if (row.parentName === prevRow.name && row.parentName && prevRow.name) {
        row.indentLevel = (prevRow.indentLevel || 0) + 1;
      }
    }
  });
}

function onNameChange() {
  // 当名称改变时，更新后续行的 parentName 选项并重新计算缩进
  rows.forEach((row, index) => {
    if (index > 0) {
      const prevRow = rows[index - 1];
      const options = getParentNameOptions(row.nodeType, index);
      if (!options.some((opt) => opt.value === row.parentName)) {
        row.parentName = options[0]?.value || "";
      }
      row.indentLevel = 0; // 重置以重新计算
      if (row.parentName === prevRow.name && row.parentName && prevRow.name) {
        row.indentLevel = (prevRow.indentLevel || 0) + 1;
      }
    }
  });
}

function removeRow(i) {
  if (rows.length <= 1) {
    return ElMessage.warning("至少保留一行，无法删除最后一行");
  }
  rows.splice(i, 1);
  if (!rows.length) addRow();
}

function copyRow(i) {
  const newRow = JSON.parse(JSON.stringify(rows[i]));
  newRow.uid = Math.random().toString(36).slice(2);
  rows.splice(i + 1, 0, newRow);
}

function clearRow(i) {
  const type = rows[i].nodeType;
  const parentName = rows[i].parentName;
  rows[i] = makeEmptyRow(parentName, type);
}

function scrollToLeft() {
  nextTick(() => {
    if (tableWrapper.value) tableWrapper.value.scrollLeft = 0;
  });
}

// 确认（校验 + 缓存）
function confirm() {
  for (let i = 0; i < rows.length; i++) {
    const r = rows[i];
    if (!r.parentName?.trim() || !r.name?.trim()) {
      return ElMessage.error(`第 ${i + 1} 行：上一级名称和名称不能为空`);
    }
  }

  if (cacheKey.value) {
    lastCache[cacheKey.value] = JSON.parse(JSON.stringify(rows));
  }

  emit("confirm", JSON.parse(JSON.stringify(rows)));
  visible.value = false;
}

// 监听关闭也缓存
watch(visible, (val) => {
  if (!val && cacheKey.value) {
    lastCache[cacheKey.value] = JSON.parse(JSON.stringify(rows));
  }
});

defineExpose({ open });
</script>

<style scoped>
.table-wrapper {
  overflow-x: auto;
  border: 1px solid #ebeef5;
  border-radius: 8px;
}
.add-btn {
  text-align: right;
  padding: 10px;
  background: #fafafa;
  border-top: 1px solid #ebeef5;
}

/* 优化表格行样式 */
:deep(.el-table__row) {
  transition: padding-left 0.2s ease;
}

/* 确保单元格内容也跟随缩进 */
:deep(.el-table__cell) {
  padding-left: inherit !important; /* 继承行的 padding-left */
}
</style>
